
function getQuery(key) {
  let arr = location.search.slice(1).split('&')
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i].split('=')
    if (item[0] === key) {
     return item[1]
    }
  }
}

const content = document.getElementById('content')
const description = document.getElementById('description')

$('.todo-edit').hide()

function revertData(data) {
  $('#content').html(data.content)
  $('#description').html(data.description)
  $('.content').val(data.content)
  $('.description').val(data.description)
}

$.ajax({
  url: `https://api.yizhanketang.cn/api/v1/todos/${getQuery('id')}`,
  success(res) {
    const data = res.data
    revertData(data)


    // console.log($('#content').html('hahaha'))
    // console.log($('#content').html())
    // console.log($('#content').text('<span>hahaha</span>'))
    // console.log($('#content').text())
    // console.log($('.content'))

    // console.log(res.data)
    // content.innerHTML = res.data.content
    // description.innerHTML = res.data.description ? res.data.description : '暂无'
    // content
    // description
  },
  error(e) {
    console.log(e)
  }
})

$('.update').click(function () {
  if ($(this).text() === '保存' && confirm('确定要提交保存？')) {
    $.ajax({
      type: 'POST',
      url: `https://api.yizhanketang.cn/api/v1/todos/${getQuery('id')}`,
      data: {
        content: $('.content').val(),
        description: $('.description').val()
      },
      success(res) {
        console.log(res)
        revertData(res.data)
        $('.todo').show()
        $('.todo-edit').hide()
        $(this).text('修改')
      },
      error() {
        alert('保存失败')
      }
    })
  } else {
    $('.todo').hide()
    $('.todo-edit').show()
    $(this).text('保存')
  }
})

$('.del').click(function () {
  if (confirm('确定要删除数据吗？')) {
    $.ajax({
      type: 'POST',
      url: `https://api.yizhanketang.cn/api/v1/todos/${getQuery('id')}/delete`,
      success() {
        location.href = 'index.html'
      },
      error() {
        alert('删除失败')
      }
    })
  }
})

// console.log(getQuery('id'))

